/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.ormlite;

import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.SqlType;
import com.j256.ormlite.field.types.BaseDataType;
import com.j256.ormlite.misc.SqlExceptionUtil;
import com.j256.ormlite.support.DatabaseResults;
import net.apexes.commons.lang.Dates;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class AdaptiveDateStringType extends BaseDataType {

    private static final AdaptiveDateStringType singleTon = new AdaptiveDateStringType();

    public static AdaptiveDateStringType getSingleton() {
        return singleTon;
    }

    protected AdaptiveDateStringType() {
        super(SqlType.STRING);
    }

    @Override
    public Object javaToSqlArg(FieldType fieldType, Object obj) throws SQLException {
        return Dates.format((Date) obj, fieldType.getFormat());
    }

    @Override
    public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
        String dateStr = (String) sqlArg;
        return parseDefaultString(fieldType, dateStr);
    }

    @Override
    public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException {
        try {
            return Dates.parseAdaptive(defaultStr);
        } catch (ParseException e) {
            throw SqlExceptionUtil.create("Problems with field " + fieldType
                    + " parsing date-string '" + defaultStr, e);
        }
    }

    @Override
    public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
        return results.getString(columnPos);
    }

    @Override
    public Object resultStringToJava(FieldType fieldType, String sqlArg, int columnPos) throws SQLException {
        return sqlArgToJava(fieldType, sqlArg, columnPos);
    }

    @Override
    public boolean isValidForField(Field field) {
        return (field.getType() == Date.class);
    }

    @Override
    public int getDefaultWidth() {
        return 20;
    }
}
